/*
 *
 *  Copyright (C) 2012-2024
 *  All rights reserved, Designed By 杭州连线客信息技术有限公司
 *  注意：
 *  本软件为杭州连线客信息技术有限公司开发研制，未经购买不得使用
 *  购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 *  一经发现盗用、分享等行为，将追究法律责任，后果自负
 *
 */

package com.lxk.oms.flow.pay;

import com.lxk.event.helper.EventHelper;
import com.lxk.event.oms.OrderOptionLogEvent;
import com.lxk.event.oms.enums.OrderEnums;
import com.lxk.oms.order.domain.vo.OmsOrderVo;
import com.lxk.oms.order.service.IOmsOrderService;
import com.lxk.service.ums.response.UmsUserDto;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.FlowExecutor;
import com.yomahub.liteflow.core.NodeComponent;
import com.yomahub.liteflow.log.LFLog;
import com.yomahub.liteflow.log.LFLoggerManager;
import lombok.AllArgsConstructor;
import org.dromara.common.core.exception.ServiceException;

import java.util.List;

/**
 * 订单支付中处理节点
 *
 * @author heyi
 * 2024/8/22
 */
@LiteflowComponent(value = FlowPayOrderNodeConst.PAY_ING_NODE)
@AllArgsConstructor
public class OrderPayingNode extends NodeComponent {
    private final IOmsOrderService omsOrderService;
    private final LFLog log = LFLoggerManager.getLogger(FlowExecutor.class);

    @Override
    public void process() throws Exception {
        PayContext contextBean = getContextBean(PayContext.class);
        List<OmsOrderVo> omsOrderList = contextBean.getOmsOrder();
        omsOrderList.forEach(omsOrder -> {
            Boolean success = omsOrderService.updateOrderStatus(omsOrder.getId(), OrderEnums.OrderStatus.CREATE_0, OrderEnums.OrderStatus.PAYING_100);
            // 用户重复支付的问题，看下订单是否处于支付中，后续可能用缓存来处理，
            // 目前会有并发问题：支付订单号可能会被覆盖掉，造成用户支付，订单状态未改变的问题
            if (!success) {
                success = omsOrderService.updateOrderStatus(omsOrder.getId(), OrderEnums.OrderStatus.PAYING_100, OrderEnums.OrderStatus.PAYING_100);
            }
            if (!success) {
                OmsOrderVo omsOrderVo = omsOrderService.queryById(omsOrder.getId());
                Integer status = omsOrderVo.getStatus();
                String name = OrderEnums.OrderStatus.getByCode(status).getName();
                log.error("订单状态异常，状态为:{}", name);
                throw new ServiceException("订单状态为" + name);
            }
        });
    }

    @Override
    public void onSuccess() throws Exception {
        PayContext contextBean = getContextBean(PayContext.class);
        OrderOptionLogEvent createEvent = new OrderOptionLogEvent();
        List<OmsOrderVo> omsOrderList = contextBean.getOmsOrder();
        omsOrderList.forEach(omsOrder -> {
            UmsUserDto umsUserDto = contextBean.getUser();
            Long merId = omsOrder.getMerId();
            Long userId = umsUserDto.getUserId();
            String nickName = umsUserDto.getNickName();
            createEvent.setTenantId(contextBean.getTenantId());
            createEvent.setOrderSn(omsOrder.getOrderNo());
            createEvent.setUserId(userId);
            createEvent.setMerId(merId);
            createEvent.setOrderLogEnums(OrderOptionLogEvent.OrderLogEnums.ORDER);
            createEvent.setUserType(umsUserDto.getUserType());
            createEvent.setContent(
                OrderOptionLogEvent.OrderContentFormatEnums.PAY_ORDER.formatContent(nickName,
                    omsOrder.getOrderNo(),
                    OrderEnums.PayType.getByCode(contextBean.getPayType()).getName())
            );
            EventHelper.publishEvent(createEvent);
        });

    }
}
